﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Kele.Activity.Helper
{
    public class StringJsonConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var sValue = value.ToString().Trim();
            if (string.IsNullOrWhiteSpace(sValue))
            {
                writer.WriteNull();
                return;
            }

            try
            {
                var t = JToken.Parse(sValue);
                writer.WriteRawValue(t.ToString(Formatting.None));
            }
            catch (Exception)
            {
                writer.WriteNull();
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            return JToken.Load(reader).ToString(Formatting.None); ;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(string)  ;
        }
    }
}